﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace ConsoleApp
{
    /// <summary>
    /// 代码注入
    /// </summary>
    public class UnityHelper
    {
        //ioc容器
        private static IUnityContainer container;

        static UnityHelper()
        {
            container = new UnityContainer();//1.定义容器
        }

        public static T GetBean<T>()
        {
            container.RegisterType<T, T>();//2.命名注册
            return container.Resolve<T>();//3.解析默认对象
        }
    }

    public interface IIoc
    {
        void Print(string msg);
    }

    public class Ioc : IIoc
    {
        public void Print(string msg)
        {
            Console.WriteLine(msg);
        }
    }
    /// <summary>
    /// 执行顺序：先执行构造函数注入，在执行属性注入，最后执行方法注入
    /// </summary>
    public class IocExample
    {
        //属性注入
        [Dependency]
        public IIoc ioc1 { get; set; }

        private IIoc ioc2;

        private IIoc ioc3;

        //构造函数注入
        [InjectionConstructor]
        public IocExample(IIoc ioc2)
        {
            this.ioc2 = ioc2;
        }

        public void Work()
        {
            ioc1.Print("1");
            ioc2.Print("2");
            ioc3.Print("3");
        }

        //方法注入
        [InjectionMethod]
        public void Initialize(IIoc ioc3)
        {
             this.ioc3 = ioc3;
        }
    }
}
